package cn.dakaqi.apps.group.admin.utils;

import com.mangofactory.swagger.annotations.ApiIgnore;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by chunyang on 2016/5/13.
 */
@RestController
@RequestMapping(value = "/upload")
@ApiIgnore
public class UploadImgController
{
    /**
     * 上传教师图片.
     */
    @ResponseBody
    @RequestMapping(value = "/uploadTeacherIMG")
    public void uploadImg(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        SimpleDateFormat simpleFormat = new SimpleDateFormat("MMddHHmmsss");
        String generationfileName = simpleFormat.format(new Date()) + new Random().nextInt(1000);
        //保存路径
        String savePath = "D:/";
        String updateP = request.getParameter("updateP");
        String fileNameSuffix = null;
        String fileName = null;
        if (null != updateP && !"".equals(updateP))
        {
            try
            {
                MultipartFile mf = request.getFile(updateP);
                fileName = mf.getOriginalFilename();
                if (null != mf && !"".equals(mf))
                {
                    fileNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                    SaveFileFromInputStream(mf.getInputStream(), savePath, generationfileName + "." + fileNameSuffix);
                    out.write("{'state':'0','fileName':'" + generationfileName + "." + fileNameSuffix + "','updateP':'" + updateP + "'}");
                }
            } catch (Exception e)
            {
                out.write("{'state':'1'}");
                e.printStackTrace();
            }
        }
    }

    //保存文件   1,文件   2，保存路径 3，文件名称
    public void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException
    {
        FileOutputStream fs = new FileOutputStream(path + "/" + filename);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1)
        {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }

}
